package com.asset.dispoal.business.casedispose.service.command;

import com.asset.dispoal.business.bsCase.domain.db.entity.BsCase;
import com.asset.dispoal.business.bsCase.domain.db.entity.BsCaseMediation;
import com.asset.dispoal.business.bsCase.domain.db.mapper.BsCaseMapper;
import com.asset.dispoal.business.casedispose.dto.CaseDisposeMediationDetailUpdateRequest;
import com.asset.dispoal.business.casedispose.dto.CaseDisposeMediationUpdateRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tech.mhuang.pacebox.core.date.DateTimeUtil;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.id.BaseIdeable;
import tech.mhuang.pacebox.core.util.StringUtil;
import tech.mhuang.pacebox.springboot.core.local.GlobalHeaderThreadLocal;
import tech.mhuang.pacebox.springboot.protocol.Result;

import java.util.Date;

@Component
public class CaseDisposeUpdateMediationCommand implements BaseCommand<CaseDisposeMediationUpdateRequest, Result> {

    @Autowired
    BsCaseMapper caseMapper;

    @Autowired
    BaseIdeable<String> ideable;

    @Override
    public Result execute(CaseDisposeMediationUpdateRequest request) {
        String userId = GlobalHeaderThreadLocal.get().getUserId();
        Date currentDate = DateTimeUtil.currentDate();
        BsCase bsCase = new BsCase();
        bsCase.setId(request.getId());
        bsCase.setOperateUser(userId);
        bsCase.setOperateTime(currentDate);
        bsCase.setPrepaymentPeriod(request.getPrepaymentPeriod());
        caseMapper.mediation(bsCase);
        caseMapper.deleteMediationById(bsCase.getId());
        for (CaseDisposeMediationDetailUpdateRequest detail : request.getDetailList()) {
            BsCaseMediation caseMediation = new BsCaseMediation();
            if (StringUtil.isEmpty(detail.getId())) {
                caseMediation.setId(ideable.generateId());
            }
            caseMediation.setCaseId(request.getId());
            caseMediation.setPrepaymentTime(detail.getPrepaymentTime());
            caseMediation.setPeriod(detail.getPeriod());
            caseMediation.setPrepaymentPrincipal(detail.getPrepaymentPrincipal());
            caseMediation.setPrepaymentInterest(detail.getPrepaymentInterest());
            caseMediation.setPrepaymentPenalty(detail.getPrepaymentPenalty());
            caseMapper.insertMediation(caseMediation);
        }
        return Result.ok();
    }
}
